<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2016 http://uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: UCT <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\shop\controller;

use app\admin\controller\Admin;
use think\Db;
use \think\Loader;
use app\admin\builder\AdminConfigBuilder;
use app\admin\builder\AdminListBuilder;
use app\admin\builder\AdminTreeListBuilder;
//use Think\Db\Driver\Pdo;


class Shop extends Admin
{
    protected $product_cats_model;
    protected $product_model;
    protected $order_model;
    protected $delivery_model;
    protected $message_model;
    protected $coupon_model;
    protected $user_coupon_model;
    protected $address_model;
    protected $product_comment_model;

	protected $order_logic;
	protected $coupon_logic;

    function _initialize()
    {
        $this->product_cats_model = model('ShopProductCats');
	    $this->product_model = model('ShopProduct');
	    $this->order_model = model('ShopOrder');
	    $this->order_logic = model('ShopOrder','Logic');
	    $this->coupon_logic = model('ShopCoupon','Logic');
        parent::_initialize();
    }


	public function index()
	{
		if(!modC('MP_ID', '', 'Shop'))
		{
			//未配置公众号
			redirect(url('shop/shop'));
		}
		else
		{
			redirect(url('shop/product'));
		}
	}

	public function shop()
	{

		$member_public = db('member_public')->column('id,public_name');
		array_unshift($member_public,'选择公众号');
		return $this->fetch();

	}
    /*
        * 幻灯片
        */
    public function slides($action='')
    {
        $shop_slides_model = db('shop_slides');
        switch ($action)
        {
            case 'add':
                if(request()->isPost())
                {
                    $slides = input('post.');

                    //拼接url
                    $mp_id = explode('-',$slides['mp_id']);
                    unset($slides['mp_id']);
                    if (!empty($slides['link'])) {
                        $slides['link'] = $slides['link'] . '/mp_id/' . $mp_id[1];
                    }
                    trace($slides,'提交数据');
                    $slide['sort'] = (empty($slide['sort'])?0:$slide['sort']);
                    if(strlen($slides['title'])>255)
                    {
                        return ['status'=>true,'info'=>'说明不要长于255个字符'];
                    }

                    if(empty($slides['image']))
                    {
                        return ['status'=>true,'info'=>'请设置一张图片'];
                    }
                    if(!empty($slides['id']))
                    {
                        unset($slides['create_time']);
                        $ret = $shop_slides_model->where('id',$slides['id'])->update($slides);
                    }
                    else
                    {
                        $ret = $shop_slides_model->insert($slides);
                    }
                    if($ret)
                    {
                        return ['status'=>true,'info'=>'添加成功'];
                    }
                    else
                    {
                        return ['status'=>true,'info'=>'添加失败'];
                    }
                }
                else
                {
                    $id = input('id');
                    if(!empty($id)){
                        $slides = $shop_slides_model->where('id ='.$id)->find();
                        $slides['image_id'] = $slides['image'];
                        $slides['image'] = get_cover($slides['image'],'url');
                        //输出公众号mp_id
                        $slides['wechat'] = model('member_public')->select();
                        $this->assign('list',$slides);
                    }

                    return $this->fetch('slides_add');
                }
                break;
            case 'delete':
                $ids = input('ids');
//                is_array($ids) || $ids = array($ids);
                $ret = $shop_slides_model->delete($ids);
//                $ret = $shop_slides_model->where('id in ('.implode(',',$ids).')')->delete();
                if($ret)
                {
                    return ['status'=>true,'info'=>'删除成功'];
                }
                else
                {
                    return ['status'=>true,'info'=>'删除失败'];
                }
                break;
            default:
                $page = input('page',1);//页数
                $r = input('r',10);//每页显示数
                $slides = $shop_slides_model->where('status',0)->order('sort desc,create_time desc')->select();

                $page = $shop_slides_model->where('status',0)->paginate($r,true,['page'=>$page])->render();//页数
                foreach ($slides as &$row){
                    $row['image'] = get_cover($row['image'],'url');
                }
                $this->assign('list',$slides);
                $this->assign('page',$page);
                return $this->fetch();
                break;
        }
    }

	/*
	 * 商品分类
	 */
	public function product_cats($action='',$page=1,$r=10)
	{

		switch($action)
		{
			case 'add':
			    //输出级联列表
                $cate = $this->product_cats_model->select();
                $this->assign("tag",$cate);
				if(request()->isPost())
				{
					$product_cats = input('');//$this->product_cats_model->create();
					if (!$product_cats){
						$this->error($this->product_cats_model->getError());
					}
					//不能把自己或者自己的子类当作上级目录
					if(!empty($product_cats['parent_id'] )	&& (($product_cats['parent_id'] ==$product_cats['id']) ))
					{
						return ['status'=>true,'info'=>'不要选择自己分类或自己的子分类'];
					}

                    //添加或者编辑数据
					$ret = $this->product_cats_model->add_or_edit_product_cats($product_cats);
					if ($ret)
					{

                        return ['data'=>'','status'=>true,'info'=>'操作成功。', 'url'=>url('shop/product_cats',array
                        ('parent_id'=>input('parent_id',0)))];
					}
					else
					{
                        return ['data'=>'','status'=>true,'info'=>'操作失败'];
					}
				}else
				{
				    $parent_id = input('parent_id');
                    //获取当前下属类别
                    if($parent_id != 0)
                    {
                        $product_cats = $this->product_cats_model->get_all_cat_id_by_pid($parent_id);
                    }
					$id = input('id');
					if(!empty($id))
					{
						$product_cats = $this->product_cats_model->get_product_cat_by_id($id);
					}
					else
					{
						$product_cats = array();
					}
                    $this->assign('list',$product_cats);
					return $this->fetch('add');
				}
				break;
			case 'delete':
				$ids = input('ids');
				$ret = $this->product_cats_model->delete_product_cats($ids);
				if ($ret)
				{

					return ['status'=>true,'info'=>'删除成功。', url('shop/product_cats')];
				}
				else
				{
					$this->error('删除失败。');
				}
				break;
			default:

				$option['parent_id'] = input('parent_id',0,'intval');
				if(!empty($option['parent_id']))
				{
					$parent_cat  = $this->product_cats_model->get_product_cat_by_id($option['parent_id']);
				}
				if(input('all')) $option = array();
				$option['page'] = $page;
				$option['r']  =  $r;
				$cats = $this->product_cats_model->get_product_cats($option);
                //var_dump($cats['list']);
				$totalCount = $cats['count'];
				$select = $this->product_cats_model->get_produnct_cat_list_select();
				$this->assign('list',$cats['list']);//输出数据列表
                $this->assign('page',$cats['page']);
				return $this->fetch();
		}
	}

	/*
	 * 商品相关
	 */
	public function product($action = '')
	{
		switch($action)
		{
			case 'add':
                if (request()->isPost()){
                    $price1 = input('post.price1/a');
                    $price2 = input('post.price2/a');
                    $data = input('');
                    trace($data,'data');
                    if (is_array($price1) && isset($price1) && isset($price2)){
                        $str = array();
                        for ($i=0;$i<count($price1);$i++){
                            if ($price2[$i] != '' && $price1[$i] != ''){
                                $str[$i] = $price1[$i] .'￥'.$price2[$i];
                            }
                        }
                        $data['price_int'] = implode(',',$str);
                    }
                    if(!empty($data['title'])){
                        $res = $this->product_model->add_or_edit_product($data);
                    }else{
                        return ['status'=>true,'info'=>'请输入标题'];
                    }
                    if($res){
                        return ['data'=>'','status'=>true,'info'=>'新增成功','url'=>url('shop/product')];
                    }else{
                        return ['status'=>true,'info'=>'更新失败'];
                    }
                }else
                {
                    $id = input('id');
                    if(!empty($id))
                    {
                        $product = $this->product_model->get_product_by_id($id);
                        $this->assign('list',$product);
                    }

                    $tag = $this->product_cats_model->where('parent_id <> 0')->select();
                    $price = $this->product_model->get_price_by_select();
                    if(count($tag)==0)
                    {
                        $this->error('先添加一个子级菜单分类吧',url('shop/product_cats',array('action'=>'add')),1);
                    }

                    $this->assign('tag',$tag);
                    $this->assign('price',$price);
                    return $this->fetch('coupon_add');
                }
                break;
			case 'delete':
				$ids = input('ids');
				$ret = $this->product_model->delete_product($ids);
				if ($ret)
				{

					return ['status'=>true,'info'=>'操作成功。', url('shop/product')];
				}
				else
				{
					return ['status'=>true,'info'=>'操作失败。'];
				}
				break;

			default:



				$option['page'] = input('page',1);//页数
				$option['r'] = input('r',10);//每页显示数
				$option['cat_id'] = input('cat_id');
                $option['status'] = input('status');
				if(empty($option['cat_id'])) unset($option['cat_id']);
				$product = $this->product_model->get_product_list($option);
				$totalCount = $product['count'];
                $page = $product['list']->render();//页码
                //分类
                $tag = $this->product_cats_model->select();
                $this->assign('tag',$tag);
                $this->assign('list',$product['list']);
                $this->assign('page',$page);
                return $this->fetch();
				break;
		}
	}

	//订单
    public function order($action = '',$order_status=0){
	    $order = model('order');
        switch ($action){
            case 'add':
                if (request()->isPost()){
                    $data = input('post.');
                    if(!empty($data)){
                        $res = $order->add_or_edit_order($data);
                    }
                    if ($res){
                        return ['status'=>true,'info'=>'新增成功','url'=>url('shop/order')];
                    }else{
                        return ['status'=>true,'info'=>'新增失败'];
                    }
                }else{
                    $id = input('id');
                    $list = $order->get_order_by_id($id);
                    $this->assign('list',$list);

                    return $this->fetch('order_add');
                }

                break;
            case 'delete':
                $ids = input('ids');
                $ret = $order->delete_order($ids);
                if($ret)
                {
                    return ['status'=>true,'info'=>'删除成功'];
                }
                else
                {
                    return ['status'=>true,'info'=>'删除失败'];
                }
                break;
            default:
                $option['order_status'] = input('order_status');
                $option['order_create_time'] = input('order_create_time');//时间范围
                //搜索字段
                $option['id'] = input('id');
                $option['mobile'] = input('mobile');

//                var_dump($_GET);
                    //设置页码
                $option['page']=input('page',1);
                $option['r']=input('r',20);
                    //读取数据
                $list = $order->get_order_list($option);
                $this->assign('status',$option['order_status']);
                $this->assign('time',$option['order_create_time']);
                $this->assign('list',$list['list']);

                return $this ->fetch();
        }

    }

    //关于我们
    public function about(){
        if (request()->isPost()){
            $data = input('post.');
            $ret = $this->product_model->edit_about($data);
            if($ret){
                return ['status'=>true,'info'=>'编辑成功'];
            }else{
                return ['status'=>true,'info'=>'编辑失败'];
            }
        }else{
            $ret = $this->product_model->get_about_by_id(1);
            $this->assign('list',$ret);
            return $this->fetch();
        }

    }

    /*
     * 价格管理设置
    */
    public function price($action = ''){
        switch ($action){
            case 'add':
                $cate = $this->product_cats_model->where('parent_id <> 0')->select();
                $this->assign("tag",$cate);
                if(request()->isPost()){
                    $data = input('post.');
                    if (isset($data)){
                        $ret = $this->product_model->add_or_edit_price($data);
                    }
                    if ($ret){
                        return ['status'=>true,'info'=>'编辑成功','url'=>url('shop/price')];
                    }else{
                        return ['status'=>true,'info'=>'编辑失败'];
                    }
                }else{
                    $id = input('id');
                    if (!empty($id)){
                        $list = $this->product_model->get_price_by_id($id);
                        $list = $list[0];
                        $this->assign('list',$list);
                    }
                    return $this->fetch('price_add');
                }
                break;
            case 'delete':
                $ids = input('ids');
                $ret = $this->product_model->delete_price($ids);
                if ($ret)
                {

                    return ['status'=>true,'info'=>'操作成功。','url'=>url('shop/price')];
                }
                else
                {
                    return ['status'=>true,'info'=>'操作失败。'];
                }
                break;
            default:
                $ret = $this->product_model->get_price_by_select();
                $this->assign('list',$ret);
                return $this->fetch();
        }

    }



//	上传文件
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $path = 'uploads/picture/';
        $info = $file->rule('uniqid')->move($path);
        if($info){
            // 成功上传后 获取上传信息

                $data= array(
                    'status'=>1,
                    'type'=>$info->getExtension(),//获取类型
                    'path'=>'/uploads/picture/'.$info->getFilename(),
                    'url'=>request()->domain(). '/uploads/picture/'.$info->getFilename(),
                    'create_time'=>time(),
                );
                $data['id'] = Db::name('picture')->insertGetId($data);
                if ($data['id']){
                    echo json_encode($data);//var_dump($info);
                    exit();
                }

        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
}
